// import Vue from 'vue';
import Vuex from 'vuex';
import axioCancel from './axioscancel/index'
import axiosInstance from '@/lib/request';

Vue.use(Vuex);


let _formatTreeData = (data) => {
  let list = [];

  function f(data, list) {
    for (let i = 0; i < data.length; i++) {
      if (data[i]) {
        list.push(data[i]);
      }
      if (data[i].children && data[i].children.length !== 0) {
        f(data[i].children, list);
      }
    }
  }

  f(data, list);
  return list;
};

let _getPathByIndex = (tree, index, path) => {

  function f(tree, index, path) {
    if (!path) {
      path = []
    }
    for (let i = 0, len = tree.length; i < len; i++) {
      let tempPath = [...path]
      tempPath.push(tree[i].path)
      if (tree[i].path === index) {
        return tempPath
      }
      if (tree[i].children) {
        return f(tree[i].children, index, tempPath)
      }
    }
  }
  return f(tree, index, path);
}

var getPathById = function(tree, index, path) {
  if (!path) {
    path = []
  }
  let tempPath = [];// 保存路径
  let count = 0;
  function deepFinds(node, target) {
    tempPath.push(node.path||node.id);
    if ((node.path||node.id) === target) {
      count++;
      return count > 0;
    }
    if (node.children) {
      for (let i = 0; i < node.children.length; i++) {
        let flag = deepFinds(node.children[i], target)
        if (!flag)
          tempPath.pop()
        else
          break;
      }
    }
    return count > 0;
  }

  for (let i = 0, len = tree.length; i < len; i++) {
    let ok = deepFinds(tree[i], index);
    if (ok) {
      break;
    } else {
      tempPath = [];
      count = 0;
    }
  }
  return tempPath;
};



const store = new Vuex.Store({
  modules: {
    home: {
      state: {
        subject: 'default',
        dialogVisible: false,
        params: null,
        isRouterAlive: true
      },
      mutations: {
        globalTheme(state, value) {
          console.info('globalTheme');
          sessionStorage.setItem('GLOBAL_THEME', value);
          state.subject = sessionStorage.getItem('GLOBAL_THEME');
          window.location.reload();  // 手动刷新才能生效
        },
        open(state, params) {
          state.params = params;
          state.dialogVisible = true;
        },
        close(state) {
          state.dialogVisible = false;
        },
        routertrue(state) {
          state.isRouterAlive = true;
        },
        routerfalse(state) {
          state.isRouterAlive = false;
        }
      },
      actions: {
        changeGlobalTheme({ commit }, data) {
          commit('globalTheme', data);
        },
        openDialog(state, params) {
          state.commit('open', params);
        },
        closeDialog(state) {
          state.commit('close');
        }
      },
      getters: {
        getGlobalTheme(state) {
          return state.subject;
        },
        getDialog(state) {
          return state.dialogVisible;
        },
        setDialog(state) {
          state.dialogVisible = false;
        }
      },
      setters: {}
    },
    userInfo: {
      state: {
        loginInfo: null
      },
      getters: {
        getLoginInfo(state) {
          return state.loginInfo;
        }
      },
      mutations: {
        setLoginInfo(state, data) {
          state.loginInfo = data;
        },
        clear(state) {
          window.localStorage.removeItem('user');
          window.sessionStorage.removeItem('user');
          state.loginInfo = null;
        }
      },
      actions: {
        buildLoginInfo({ commit },) {
          return new Promise((resolve, reject) => {
            Vue.prototype.$axiosInstance({
              url: '/getLoginInfo',
              method: 'get',
              params: {},
            }).then(result => {
              let { data, code } = result.data;
              commit('setLoginInfo', data);
              resolve(data)
            }).catch(error => {
              reject(error)
            });
          })
        },
        sessionStorageUser({ commit }, data) {
          if (!data)data={
            name: '系统管理员',
            id: -1
          };
          window.sessionStorage.setItem('user', JSON.stringify(data));
          commit('setLoginInfo', data);
        },
        localStorageUser({ commit }, data) {
          window.localStorage.setItem('user', JSON.stringify(data));
          commit('setLoginInfo', data);
        },
        clearLoginInfo({ commit }, data) {
          commit('clear');
        }
      }
    },
    authority: {
      state: {
        activePath: [],
        activeMenu: [],
        menuList: [],
        menusTree: [],
        defOpenIndex: []
      },
      getters: {
        getDefaultActive(state) {
          let active= state.menuList.find((item) => {
            return item.active;
          });
          if (active) {
            return active;
          } else {
            return state.menuList.find((item) => {
              return item.path;
            });
          }

        },
        getActivePath(state) {
          return state.activePath;
        },
        getActiveMenu(state) {
          return state.activeMenu;
        },
        getMenuData(state) {
          return {
            menusTree: state.menusTree,
            menuList: state.menuList,
            defOpenIndex: state.defOpenIndex
          }
        }
      },
      mutations: {
        clearAuthority(state) {
          state.activePath = [],
          state.activeMenu = [],
          state.menuList = [],
          state.menusTree = [],
          state.defOpenIndex = []
        },
        changeActivePath(state, data) {
          let pathIndexs = getPathById(state.menusTree, data[0]);
          let pathList = [];
          state.menuList.forEach((d) => {
            if (pathIndexs.indexOf(d.path||d.id) > -1) {
              pathList.push(d);
            }
          });
          state.activePath = pathList;
        },
        setActivePath(state, paths) {
          state.activePath = paths;
        },
        setActiveMenu(state, data) {

          let menu = state.menuList.find((d) => {
            return d.path === data[0];
          });

          let pathIndexs = getPathById(state.menusTree, data[0]);
          let pathList = [];

          state.menuList.forEach((d) => {
            if (pathIndexs.indexOf(d.path||d.id) > -1) {
              pathList.push(d);
            }
          });
          state.activeMenu = [menu, data[1]];
          state.activePath = pathList;
        },
        setMenuBreadcrumb(state, data) {

          let pathIndexs = getPathById(state.menusTree, data[0]);
          let pathList = [];

          state.menuList.forEach((d) => {
            if (pathIndexs.indexOf(d.path||d.id) > -1) {
              pathList.push(d);
            }
          });
          state.activePath = pathList;
        },
        setMenu(state, menu) {
          state.menuList = menu;
        },

        setInitData(state, data) {
          state.menusTree = data;
          state.menuList = _formatTreeData(data);
          let openIndexs = [];
          state.menusTree.forEach((d) => {
            openIndexs.push(d.path||'_'+d.id);
          });
          state.defOpenIndex = openIndexs;
        }
      },
      actions: {
        initMenuData({ commit }, menus) {
          commit('setInitData', menus);
        },
        /**
         * 同步激活菜单
         * @param state
         * @param data[]
         */
        setActiveMenuAsyn(state, data) {
          state.activeMenu = null;
          state.activePath = null;
          state.commit('setActiveMenu', data);
        },
        /**
         *  定位菜单breadcrumb
         * @param state
         * @param data[]
         */
        setBreadcrumbPath(state, data) {
          state.activePath = null;
          state.commit('setMenuBreadcrumb', data);
        },
        /**
           *  清空菜单缓存数据
           * @param commit
           * @param data
           */
        clearMenu({ commit }, data) {
          commit('clearAuthority');
        },
      }
    },
    Header: {
      state: {
        title: ''
      },
      mutations: {
        set(state, params) {
          state.title = params
        }
      },
      actions: {
        updateTitle(state, params) {
          state.commit('set', params);
        }
      },
      getters: {
        getTitle(state) {
          return state.title;
        }
      }
    },
    axioCancel
  }
});

export default store;
